use std::{default::Default, rc::Rc};
use yew::{
    function_component, html, use_context, use_effect_with_deps, use_node_ref, use_reducer,
    use_state, Callback, ContextProvider, Html, HtmlResult, Properties, Reducible,
    UseReducerHandle,
};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GeneralState {
    pub msg_show: bool,
    pub msg_text: String,
}

impl Default for GeneralState {
    fn default() -> Self {
        Self {
            msg_show: false,
            msg_text: "".to_string(),
        }
    }
}

pub enum GeneralAction {
    ShowMsg,
    HideMsg,
}

impl Reducible for GeneralState {
    type Action = GeneralAction;

    fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> {
        let next_state = match action {
            GeneralAction::ShowMsg => Self {
                msg_show: true,
                msg_text: "hello".to_string(),
            },
            GeneralAction::HideMsg => Self {
                msg_show: false,
                ..Default::default()
            },
        };
        next_state.into()
    }
}

pub type MessageContext = UseReducerHandle<GeneralState>;

#[derive(Properties, Debug, PartialEq)]
pub struct MessageProviderProps {
    #[prop_or_default]
    pub children: Html,
}

#[function_component]
pub fn MessageProvider(props: &MessageProviderProps) -> Html {
    let msg = use_reducer(|| GeneralState::default);

    html! {
        <ContextProvider<MessageContext> context={msg}>
            {props.children.clone()}
        </ContextProvider<MessageContext>>
    }
}
